<template>
    <div class="card-list-setting">
        <div class="card-setting-header">
            <div class="setting-header-left">
                <div class="setting-header-title">
                    {{ $t('common.connector.title.additionalCard') }}
                </div>
                <div class="setting-header-sub-title">
                    {{ $t('task.setting.taskTypeSetting.flow.setFlowAddCard') }}
                </div>
            </div>
            <div class="setting-header-right">
                <el-button 
                    type="primary" 
                    @click="beforeClickAddOns"
                >
                    <i class="iconfont icon-add2">
                    </i>
                    {{ $t('common.base.add2') }}
                </el-button>
            </div>
        </div>
        <!--start 附加组件列表 -->
        <div class="card-setting-list" v-if="taskCardList.length > 0">
            <task-card-item
                class="task-card-item"
                v-for="(item, idx) in taskCardList"
                :key="item.id"
                from="cardListSetting"
                :index="idx"
                :task-card="taskCardList[idx]"
                :task-type-id="taskTypeId"
                :taskTypeName="taskTypeName"
                :biz-action-code="bizActionCode"
                @finish="finishFetchTaskType"
                @deleteCard="deleteCard"
                @edit="onEditConnectorCardHandler"
                @updateAttr="obj => {
                    updateTaskCard(item, obj)
                }">
            </task-card-item>
        </div>
        <!--end 附加组件列表 -->
        <!-- start 新建附加组件 -->
        <creat-card-dialog
            :visiable.sync="isShowAddCardModal"
            @onClose="onCloseShowAddCardModal"
            :task-card-list="taskCardList"
            @update="update"
            @updateImport="updateImport"
        ></creat-card-dialog>
        <!-- end 新建附加组件 -->

        <!-- start 连接器新建弹窗 -->
        <ConnectorModuleCreateConnectorDialog
            v-if="taskTypeId"
            :title="connectorCreateModalTitle"
            :visible="isShowCreateConnectorModal"
            :bizTypeId="bizTypeId"
            :toBizType="toBizType"
            :fromBizType="fromBizType"
            :fromBizTypeName="fromBizTypeName"
            :bizActionCode="bizActionCode"
            :currentNodeId="currentNodeId"
            isShowSelectLanguage
            @close="onCloseCreateConnectorModal"
            @finish="finishFetchTaskType"
        />
        <!-- end 连接器新建弹窗 -->

        <!-- start 编辑连接器弹窗 -->
        <ConnectorModuleEditConnectorDialog
            :title="connectorEditModalTitle" 
            :fromBizTypeName="fromBizTypeName"
            :visible="isShowEditConnectorModal"
            :connectorInfo="connectorInfo"
            @close="onCloseEditConnectorModal"
            @finish="finishFetchTaskType"
        />
        <!-- end 编辑连接器弹窗 -->

        <!-- start 新建附加组件或连接器弹窗 -->
        <ConnectorModuleAddCardDialog
            :visible="isShowNewCreateCardModal"
            :is-disabled-connector="isCreateFlow"
            @cardCreate="onCardCreateHandler"
            @connectorCreate="onConnectorCreateHandler"
            @close="onCloseNewCreateCardModal"
        />
        <!-- end 新建附加组件或连接器弹窗 -->
    </div>
</template>

<script>
/* component */
import CreatCardDialog from '@src/modules/setting/task/taskTypeSetting/flow/components/TaskCard/CreatCardDialog.vue';
import TaskCardItem from '@src/modules/setting/task/taskTypeSetting/flow/components/TaskCardItem.vue';
/* api */
import * as SettingServiceEventApi from '@src/api/SettingServiceEventApi';
/* constant */
import { ADDITIONAL_TYPE_MAP } from '@src/modules/setting/serviceEvent/constant.js';
/* mixin */
import { ConnectorModuleCardSettingTaskMixin, ConnectorModuleCardSettingMixin } from '@src/modules/connector'
/* service */
import { isConnectorCard } from '@service/CardService';
// utils
import { cloneDeep, unionBy } from 'lodash';
import { parse } from '@src/util/querystring';
import _ from 'lodash'
import { flowMapState } from '@src/modules/setting/task/taskTypeSetting/flow/flowMap.js';

export default {
    name: 'card-list-setting',
    mixins: [ConnectorModuleCardSettingTaskMixin, ConnectorModuleCardSettingMixin],
    components: {
        [TaskCardItem.name]: TaskCardItem,
        [CreatCardDialog.name]: CreatCardDialog,
    },
    props: {
        taskTypeName: {
            type: String,
            default: '',
        },
        bizActionCode:{
            type:String,
            default:''
        },
        flowCardList: {
            type: Array,
            default: () => ([]),
        },
        currentNodeId: {
            type:String,
            default:''
        },
        isNewNormalNode: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        return {
            taskTypeId: '',
            oldCardInfo: [],
            cardSysList: [], // 模板库列表
            authInfo: [],
            currentFlow: '', // 当前节点
            excludedCurrentCardList: [], // 不在本节点的附加组件
        }
    },
    computed: {
      isNormalNode() {
        return this.bizActionCode === 'normal'
      },
        taskCardList: {
            get() {
                const includedList = [];
                const excludedList = [];
                // 工单自定义节点的stateCanEdit存的是id，所以需要特殊处理下获取附加组件
                const currentFlow = this.isNormalNode ? this.currentNodeId : flowMapState[this.bizActionCode];

                this.flowCardList.forEach(item => {
                    if ((item.stateCanEdit || []).some(x=> x === currentFlow)) {
                        includedList.push(item);
                    }else {
                        excludedList.push(item);
                    }
                });
                this.excludedCurrentCardList = excludedList;

                return includedList;
            },
            set(val) {
                this.$emit('flowCardChange', unionBy(this.excludedCurrentCardList, val, 'id'));
            }
        },
        // 是否为新建节点
        isCreateFlow() {
            return this.bizActionCode === 'create';
        },
    },
    mounted() {
        let query = parse(window.location.search) || {};
        this.taskTypeId = query.taskTypeId;
    },
    methods: {
      // 校验当前节点是否是新节点
        async beforeClickAddOns() {
          try {
            // 判断当前节点是否还没有保存
            if(this.isNewNormalNode) {
              await this.$confirm(this.$t('event.setting.serviceEventTypeSetting.flow.tips2'), '', {
                confirmButtonText: this.$t('common.base.save'),
                cancelButtonText: this.$t('common.base.notSaveForNow'),
                type: 'warning',
                closeOnClickModal: false
              })
              this.$eventBus.$emit('task_custom_node_save', true, this.onClickCreateHandler);
            }else {
              this.onClickCreateHandler();
            }
          }catch (e) {
            console.error(e)
          }
        },
        // 从已添加的组件库选择
        update(newCard) {
            let list = [];
            const oldList = cloneDeep(this.taskCardList);
            const cardIdMap = new Map();
            newCard.forEach(item=>{
                cardIdMap.set(item.id, item)
            })
            oldList.forEach(item=>{ // 保留原数据
                if(cardIdMap.has(item.id)){
                    list.push(item);
                    cardIdMap.delete(item.id)
                }else if(item.type !== 8){ // 只针对附加组件修复
                  // 删除的附加组件：因为在节点删除，只能移除taskCardList的stateCanEdit（bizActionCode）
                  item.stateCanEdit = item.stateCanEdit?.filter(item => item !==  flowMapState[this.bizActionCode])
                  if(item.stateCanEdit?.length) {
                    this.$set(item, 'delCurrentNode',  true)
                    list.push(item);
                  }
                }
                if(item.type === 8) {
                    // 这里还需要添加上已经的连接器附加组件
                    list.push(item);
                }
            });
            let newList = [...cardIdMap.values()];
            newList = newList.map(item=>Object.assign(item, {notNullFlow: null, stateCanEdit: null, authInfo:this.authInfo, isSetObject: 'add'}))
            list.push(...newList);

            // 设置当前节点状态给附加组件
            this.taskCardList = list.map(x => {
                let addNode = _.cloneDeep(x);
                const item = this.flowCardList.find(v => v.id === x.id);
                if(item) x = item;

                // 工单自定义节点附加组件的type特殊处理,存id
                const flow = this.isNormalNode ? this.currentNodeId : flowMapState[this.bizActionCode];
                x.stateCanEdit = x.stateCanEdit || [];

                if(!x.stateCanEdit.some(v => v === flow)) {
                    x.stateCanEdit.push(flow);
                }

                // 删除的节点
                if(addNode.delCurrentNode) {
                  x.stateCanEdit = x.stateCanEdit?.filter(item => item !== flow)
                }

                return x;
            });
            this.onCloseShowAddCardModal();
        },
        deleteCard(itemIndex) {
            // 工单自定义节点附加组件的type特殊处理,存id
            const flow = this.isNormalNode ? this.currentNodeId : flowMapState[this.bizActionCode];
            // 删除的附加组件：因为在节点删除，只能移除taskCardList的stateCanEdit（bizActionCode）
            let addon =  this.taskCardList[itemIndex]
            if(addon?.stateCanEdit?.length === 1) {
              // 此时stateCanEdit为空的时候再移除
              this.taskCardList = this.taskCardList.filter((item, index) => index !== itemIndex);
            }else {
              addon.stateCanEdit = addon.stateCanEdit?.filter(item => item !== flow)
            }

            this.$platform.notification({
                title: this.$t('common.base.deleteSuccess'),
                type: 'success'
            });
        },
        updateTaskCard(cardList, updateObj) {
            for (const key in updateObj) {
                if (updateObj.hasOwnProperty(key)) {
                    cardList[key] = updateObj[key];
                }
            }
        },
        // 查询最新添加的连接器数据
        finishFetchTaskType(){
            this.$emit('flowCardChange');
        },
        // 从模版库中选择更新数据
        updateImport(newCard){
            let newTaskCard = Object.assign(newCard, {notNullFlow: null, stateCanEdit: null, authInfo:this.authInfo, isSetObject: 'add'});
            this.taskCardList = [...this.taskCardList, newTaskCard];

            this.onCloseShowAddCardModal();
        },
        /* 查询模板库列表 */
        fetchTemplateLibraryList() {
            SettingServiceEventApi.getSystemTemplateList({ id: 1 })
                .then(res => {
                    const { status, message, data = [] } = res;

                    if (status == 0) {
                        // TODO-bdz 中文判断
                        this.cardSysList = data.filter(card => card.cardName !== '工时记录')
                        .map(item => {
                            return {
                                ...item,
                                type: ADDITIONAL_TYPE_MAP[item.cardId],
                            };
                        });
                    } else {
                        this.$message.error(message);
                    }
                })
                .catch(err => console.error(err))
        },
    }
}
</script>

<style lang="scss" scoped>
.card-list-setting {
    .card-setting-header {
        display: flex;
        justify-content: space-between;
        .setting-header-title {
            font-size: 14px;
            font-weight: 600;
            color: #262626;
            line-height: 14px;
        }
        .setting-header-sub-title {
            font-size: 12px;
            font-weight: 400;
            color: #8C8C8C;
            line-height: 28px;
        }
        .setting-header-right {
            .el-button {
                width: 85px;
            }
        }
    }

    .card-setting-list{
        display: flex;
        flex-flow: wrap;
        align-items: center;
        width: calc(100% + 12px);
        .task-card-item {
            width: 328px !important;
            margin: 0 12px 12px 0;
            border: 1px solid #F5F5F5;

            &:hover {
                box-shadow: none;
            }
        }
        .task-card {
            cursor: default;
        }

        @media screen and (max-width: 1920px) {
            .task-card-item {
                width: 328px;
            }
        }
    }

}
</style>